import { existsSync, writeFileSync } from 'fs';
import { join } from "path";
import { ITableOutput, IWriter } from "../../inters/InterfaceApi";
import { mkdirsSync } from '../../utils/CpFile';
import { logout } from '../../utils/LogUtil';
import { convertMgr } from '../mgr/ConvertMgr';

export class JsonMergeWriter implements IWriter {

    private _cfg: ITableOutput;
    protected _platFile: any;

    write(data: any, options?: any, callback?: (res?: any) => void) {
        
        // let path = options.path;
        this._cfg = data;
        if (!this._cfg.merge) {
            logout('当前没有合并的配置')
            return;
        }
        let fileContent = {};

        let convert = convertMgr.crtConvert;
        let tableData = convert.tableData;

        for (let table in tableData) {
            let td = tableData[table];
            if(td.data==null)continue;
            // 先将所有的json都导出
            let str = JSON.stringify(td.data);
            fileContent[table] = Buffer.from(str);
        }

        if (this._cfg.merge && this._cfg.merge.length) {

            // todo 这里只实现了合并第一组文件，默认是所有都合并的
            let mergeData = this._cfg.merge[0];

            let headObj = {};
            let index = 0;
            for (let key in fileContent) {
                // if (key.substr(key.length - 5) != '.json') {
                //     continue;
                // }
                let content: Buffer = fileContent[key];
                if (content.length <= 0) {
                    continue;
                }
                headObj[key] = [index, content.length];
                index += content.length + 1;
            }
            var headBuff = Buffer.from(JSON.stringify(headObj));
            var contentBuff = Buffer.alloc(4 + headBuff.length + index - 1);
            contentBuff.writeUInt32LE(headBuff.length, 0);
            contentBuff.fill(headBuff, 4);

            for (var key in headObj) {
                var [start, len] = headObj[key];
                contentBuff.fill(fileContent[key], start + 4 + headBuff.length);
            }

            let dir = mergeData.path;//join(path, mergeData.path);
            if (!existsSync(dir)) {
                mkdirsSync(dir);
            }
            let fileName = `${mergeData.name}${mergeData.nameExt}`;

            if (!!mergeData.compress) {
                let zlib = require("zlib");
                let result = zlib.deflateRawSync(contentBuff);
                writeFileSync(join(dir, fileName), result);
            } else if (!mergeData.compress) {
                writeFileSync(join(dir, fileName), contentBuff);
            }
        }
    }
}